import { parse, HTMLElement } from 'node-html-parser';
//import { NodeHtmlMarkdown} from 'node-html-markdown';
import turndown from 'turndown';
import Path from "path";

export class Flomo {
    memos: Record<string, string>[];
    tags: string[];
    files: Record<string, string[]>;
    startDate: Date;
    endDate: Date;

    constructor(flomoData: string, startDate: Date, endDate: Date) {
        //const root = parse(DOMPurify.sanitize(flomoData));
        this.startDate = startDate;
        this.endDate = endDate;
        const root = parse(flomoData);
        this.memos = this.loadMemos(root.querySelectorAll(".memo"));
        this.tags = this.loadTags(root.getElementById("tag").querySelectorAll("option"));
        this.files = {};
    }

    private included(memoDate: Date, startDate: Date, endDate: Date): boolean {
        if (startDate && endDate) {
            return memoDate >= startDate && memoDate <= endDate;
        } else if (startDate) {
            return  memoDate >= startDate;
        } else if (endDate) {
            return  memoDate <= endDate;
        } else {
            return true;
        }
    }

    private loadMemos(memoNodes: Array<HTMLElement>): Record<string, string>[] {

        const res: Record<string, string>[] = [];
        const extrtactTitle = (item: string) => { return item.replace(/(-|:|\s)/gi, "_") }
        const extractContent = (content: string) => {
            //return NodeHtmlMarkdown.translate(content, {bulletMarker: '-',}).replace('\[', '[').replace('\]', ']')
            //return NodeHtmlMarkdown.translate(content, {bulletMarker: '-',}).replace('\[', '[').replace('\]', ']')
            //return (new showdown.Converter({metadata: false})).makeMarkdown(content)
            //return NodeHtmlMarkdown.translate(content, {bulletMarker: '-'})
            let turndownContent = (new turndown()).turndown(content);
            turndownContent = turndownContent.replaceAll("\n\n", "\n"); // 换行的笔记两条中间会有</p>和<p>被误认为两个换行符，这里替换成一个。
            if (content.indexOf("<img") !== -1) {
                const regex = /\((.*?)\)/;
                const match = turndownContent.match(regex);
                if (match) {
                    const attachmentFilePath = match[1];
                    const attachmentFileBasename = Path.basename(attachmentFilePath);
                    return `![[${attachmentFileBasename}#inline|300]]`;
                } else {
                    throw Error("img src not match.");
                }
            } else {
                return turndownContent;
            }

            // return (new turndown()).turndown(content)
            //                             .replace(/\\\[/g, '[')
            //                             .replace(/\\\]/g, ']')
            //                             //replace(/\\#/g, '#')
            //                             .replace(/!\[\]\(file\//gi, "\n![](flomo/")
            //                             //.replace(/\<\!--\s--\>/g, '')
            //                             //.replace(/^\s*[\r\n]/gm,'')
            //                             //.replace(/!\[null\]\(<file\//gi, "\n![](<flomo/");
        }

        memoNodes.forEach(i => {

            const dateTime = i.querySelector(".time").textContent;
            const title = extrtactTitle(dateTime);
            const content = extractContent(i.querySelector(".content").innerHTML) + "\n" +
                extractContent(i.querySelector(".files").innerHTML);

            const memoDate = new Date(dateTime.split(" ")[0]);

            // if (memoDate > this.startDate) { // JM: BatchDate之前的数据就不用处理了
            if (this.included(memoDate, this.startDate, this.endDate)) {
                res.push({
                    "title": title,
                    "date": dateTime.split(" ")[0],
                    "datetime": dateTime,
                    "time": dateTime.split(" ")[1],
                    "content": content,
                })
            }
        });

        return res;
    }

    private loadTags(tagNodes: Array<HTMLElement>): string[] {
        const res: string[] = [];

        tagNodes.slice(1).forEach(i => { res.push(i.textContent); })

        return res;

    }


}
